<?php

namespace app\admin\model\course;

use app\common\model\User;
use think\Model;


class Spell extends Model
{





    // 表名
    protected $name = 'course_spell';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        "start_time_text",
        "end_time_text",
    ];


    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
            $changed = $row->getChangedData();
            if(isset($changed['start_time']) && isset($changed['end_time'])){
                if($changed['end_time'] <= $changed['start_time']){
                    exception("结束时间必须大于开始时间");
                }
            }
            if(isset($changed['user_num']) && $changed['user_num']<=0){
                exception("请设置拼团总人数");
            }
            if(isset($changed['team_num']) && $changed['team_num']<=0){
                exception("请设置成团人数");
            }
        });

        self::beforeUpdate(function ($row) {
            $changed = $row->getChangedData();
            if(isset($changed['start_time']) && isset($changed['end_time'])){
                if($changed['end_time'] <= $changed['start_time']){
                    exception("结束时间必须大于开始时间");
                }
            }
            if(isset($changed['user_num']) && $changed['user_num']<=0){
                exception("请设置成团人数");
            }
            if(isset($changed['team_num']) && $changed['team_num']<=0){
                exception("请设置团队数量");
            }
        });

    }




    protected function setStartTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setEndTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function getStartTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['start_time']) ? $data['start_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getEndTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['end_time']) ? $data['end_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }





    public function course()
    {
        return $this->belongsTo('app\admin\model\course\Course', 'course_id', 'id', [], 'RIGHT')->setEagerlyType(0);
    }

    public function admincourse()
    {
        return $this->belongsTo('app\admin\model\course\Course', 'course_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    /*
     * 获取课程列表
     * */
    public function getList($condition = [],$paginate = 1, $limit = 15){
        $list = $this->with(["course"=>function($query){
            $query->withField("id, name, image,price,desc,class_hour");
        }])->where("spell.switch",1)
            ->where("start_time","<",time())
            ->where("end_time",">",time())
            ->order("start_time","desc")
            ->where($condition);
        if($paginate == 1){
            $list = $list->paginate();
        }else{
            $list = $list->limit($limit)->select();
        }
        $courseModel = new Course();
        foreach ($list as $key => &$value){
            $value = $this->dealSpellInfo($value);
            $value["course"] = $courseModel->dealInfo($value["course"]);
        }
        return $list;
    }

    /*
     * 获取详情
     * */
    public function getInfo($condition = [],$user = null,$lat = '', $lng='',$show_error = true){
        $info = $this->where($condition)
            ->where("switch",1)
            ->find();
        if(!$info && $show_error){
            exception("未找到当前拼团");
        }
        if($info){
            $courseModel = new \app\admin\model\course\Course();
            $courseCondition = [
                "id" => $info['course_id']
            ];
            $info = $this->dealSpellInfo($info);
            $spellUserList = $this->getSpellUserList($info);
            $info['user_list'] = $spellUserList['user_list'];
            $info['team_count'] = $spellUserList['team_count'];
            $info['course'] = $courseModel->getInfo($courseCondition,$user,$lat,$lng);
        }

        return $info;
    }

    public function dealSpellInfo($info){
        $info['buy_num'] = $this->spellUserNum($info['id'],$info['course_id']);
        $surplus_num = bcmul($info['user_num'],$info['team_num']) - $info['buy_num'];
        $info['surplus_num'] = ($surplus_num <=0 ?0:$surplus_num);
//        $info['user_num'] = bcmul($info['user_num'],$info['team_num']);
        return $info;
    }

    /*
     * 拼团人数
     * $mode 1 返回人数 2 检测
     * */
    public function spellUserNum($spell_id,$course_id,$team_id = 0,$mode = 1){
        $spellInfo = $this::where("id",$spell_id)->find();

        if(!$spellInfo){
            exception("未找到当前拼团信息");
        }

        $buy_spell_num = Order::where([
            "spell_id" => $spell_id,
            "course_id" => $course_id,
            "status" => [">=", Order::STATUS_PAY]
        ])->count();

        if($mode == 1){
            return $buy_spell_num;
        }
        $spellInfo = $this->dealSpellInfo($spellInfo);
        //判断拼团时间
        if($spellInfo['start_time'] > time()){
            exception("当前拼团未开始");
        }
        if($spellInfo['end_time'] < time()){
            exception("当前拼团已结束");
        }
        //判断人数
//        if($spellInfo['surplus_num'] <= 0){
//            exception("当前拼团总人数已满");
//        }
        //检测当前团队是否已满
        if($team_id >0){
            $team_user_num = $this->getSpellTeamUserNum($team_id);
            if($team_user_num >= $spellInfo['user_num']){
                exception("当前拼团人数已满，请选择其他拼团");
            }
        }
    }


    //获取拼团团组人数
    public function getSpellTeamUserNum($team_id){
        //团长的id 是0  要加上团长自己
        return Order::where("team_id",$team_id)->where("status",">=",Order::STATUS_PAY)->count()+1;
    }

    /*
     * 拼团人员列表
     * */
    public function getSpellUserList($info){
//        $userIds = Order::where([
//            "spell_id" => $spell_id,
//            "course_id" => $course_id,
//            "status" => [">=", Order::STATUS_PAY]
//        ])->column("user_id");
//        $list = User::where("id","in",$userIds)->field("id,nickname,avatar")->select();


        $list = Order::where([
            "order.spell_id" => $info['id'],
            "order.course_id" => $info['course_id'],
            "order.is_leader" => 1,
            "order.residue_time" => [">",time()],
            "order.team_status" => 0,
            "order.status" => [">=", Order::STATUS_PAY]
        ])->field("id,order_sn,user_id,pay_time,residue_time")
            ->with(["user"=>function($query){
                $query->withField("id,nickname,avatar");
            }])->group("order.user_id")->limit(10)->select();

        $count = Order::where([
            "order.spell_id" => $info['id'],
            "order.course_id" => $info['course_id'],
            "order.is_leader" => 1,
            "order.residue_time" => [">",time()],
            "order.team_status" => 0,
            "order.status" => [">=", Order::STATUS_PAY]
        ])->field("id,order_sn,user_id,pay_time,residue_time")
            ->with(["user"=>function($query){
                $query->withField("id,nickname,avatar");
            }])->group("order.user_id")->count();
        foreach ($list as $key => $value){

            $buy_count = $this->getSpellTeamUserNum($value['id']);
            $surplus_num = ($info['user_num'] - $buy_count);
            $value['surplus_num'] = ($surplus_num<=0)?1:$surplus_num;
        }
        return [
            "team_count" => $count,
            "user_list" => $list,
        ];
    }

}
